//
//  ScrollLoopView.m
//  WangWang
//
//  Created by he chao on 11/7/13.
//  Copyright (c) 2013 leon. All rights reserved.
//

#import "ScrollLoopView.h"

@implementation ScrollLoopView

static NSString *SG_FOCUS_ITEM_ASS_KEY = @"loopScrollview";

static CGFloat SWITCH_FOCUS_PICTURE_INTERVAL = 5.0; //switch interval time
#define ITEM_WIDTH 320.0

- (id)initWithFrame:(CGRect)frame delegate:(id<ScrollLoopViewDelegate>)delegate views:(NSArray *)views isAuto:(BOOL)autoPlay{
    self = [super initWithFrame:frame];
    if (self) {
        isAutoPlay = autoPlay;
        objc_setAssociatedObject(self, (__bridge const void *)SG_FOCUS_ITEM_ASS_KEY, views, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self setupViews];
        [self setDelegate:delegate];
    }
    return self;
}

- (void)dealloc{
    myScrollView.delegate = nil;
}

- (void)setupViews{
    NSArray *views = objc_getAssociatedObject(self, (__bridge const void *)SG_FOCUS_ITEM_ASS_KEY);
    myScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    myScrollView.scrollsToTop = NO;
    float space = 0;
    CGSize size = CGSizeMake(self.frame.size.width, 0);
    pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.frame.size.height-16-10, self.frame.size.width, 10)];
    pageControl.userInteractionEnabled = NO;
    [self addSubview:myScrollView];
    [self addSubview:pageControl];
    
    myScrollView.showsHorizontalScrollIndicator = NO;
    myScrollView.pagingEnabled = YES;
    
    pageControl.numberOfPages = views.count>1?views.count-2:views.count;
    pageControl.currentPage = 0;
    
    myScrollView.delegate = self;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)];
    tapGestureRecognizer.delegate = self;
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [myScrollView addGestureRecognizer:tapGestureRecognizer];
    myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width*views.count, myScrollView.frame.size.height);
    for (int i = 0; i < views.count; i++) {
        UIView *vi = [views objectAtIndex:i];
        vi.frame = CGRectMake(i*myScrollView.frame.size.width+space, space, myScrollView.frame.size.width-2*space, myScrollView.frame.size.height-2*space-size.height);
        [myScrollView addSubview:vi];
    }
    if ([views count]>1) {
        [myScrollView setContentOffset:CGPointMake(ITEM_WIDTH, 0) animated:NO];
        if (isAutoPlay)
        {
            [self performSelector:@selector(switchFocusImageItems) withObject:nil afterDelay:SWITCH_FOCUS_PICTURE_INTERVAL];
        }
    }
    
}

- (void)switchFocusImageItems
{
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(switchFocusImageItems) object:nil];
    
    CGFloat targetX = myScrollView.contentOffset.x + myScrollView.frame.size.width;
    NSArray *views = objc_getAssociatedObject(self, (__bridge const void *)SG_FOCUS_ITEM_ASS_KEY);
    targetX = (int)(targetX/ITEM_WIDTH) * ITEM_WIDTH;
    [self moveToTargetPosition:targetX];
    
    if ([views count]>1 && isAutoPlay)
    {
        [self performSelector:@selector(switchFocusImageItems) withObject:nil afterDelay:SWITCH_FOCUS_PICTURE_INTERVAL];
    }
    
}

- (void)moveToTargetPosition:(CGFloat)targetX
{
    BOOL animated = YES;
    //    NSLog(@"moveToTargetPosition : %f" , targetX);
    [myScrollView setContentOffset:CGPointMake(targetX, 0) animated:animated];
}

- (void)singleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    NSLog(@"%s", __FUNCTION__);
    NSArray *views = objc_getAssociatedObject(self, (__bridge const void *)SG_FOCUS_ITEM_ASS_KEY);
    int page = (int)(myScrollView.contentOffset.x / myScrollView.frame.size.width);
    if (page > -1 && page < views.count) {
        //        SGFocusImageItem *item = [imageItems objectAtIndex:page];
        if ([self.delegate respondsToSelector:@selector(foucusImageFrame:didSelectItem:)]) {
            //[self.delegate foucusScrollLoopView:self didSelectItem:[views objectAtIndex:page]];
        }
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float targetX = scrollView.contentOffset.x;
    NSArray *views = objc_getAssociatedObject(self, (__bridge const void *)SG_FOCUS_ITEM_ASS_KEY);
    if ([views count]>=3)
    {
        if (targetX >= ITEM_WIDTH * ([views count] -1)) {
            targetX = ITEM_WIDTH;
            [myScrollView setContentOffset:CGPointMake(targetX, 0) animated:NO];
        }
        else if(targetX <= 0)
        {
            targetX = ITEM_WIDTH *([views count]-2);
            [myScrollView setContentOffset:CGPointMake(targetX, 0) animated:NO];
        }
    }
    int page = (myScrollView.contentOffset.x+ITEM_WIDTH/2.0) / ITEM_WIDTH;
    //    NSLog(@"%f %d",_scrollView.contentOffset.x,page);
    if ([views count] > 1)
    {
        page --;
        if (page >= pageControl.numberOfPages)
        {
            page = 0;
        }else if(page <0)
        {
            page = pageControl.numberOfPages -1;
        }
    }
    if (page!= pageControl.currentPage)
    {
        if ([self.delegate respondsToSelector:@selector(foucusScrollLoopView:currentItem:)])
        {
            [self.delegate foucusScrollLoopView:self currentItem:page];
        }
    }
    pageControl.currentPage = page;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        CGFloat targetX = myScrollView.contentOffset.x + myScrollView.frame.size.width;
        targetX = (int)(targetX/ITEM_WIDTH) * ITEM_WIDTH;
        [self moveToTargetPosition:targetX];
    }
}


- (void)scrollToIndex:(int)aIndex
{
    NSArray *views = objc_getAssociatedObject(self, (__bridge const void *)SG_FOCUS_ITEM_ASS_KEY);
    if ([views count]>1)
    {
        if (aIndex >= ([views count]-2))
        {
            aIndex = [views count]-3;
        }
        [self moveToTargetPosition:ITEM_WIDTH*(aIndex+1)];
    }else
    {
        [self moveToTargetPosition:0];
    }
    [self scrollViewDidScroll:myScrollView];
    
}


@end
